﻿using RpcClient.Interface;
using RpcExtend.DAL;
using RpcExtend.Model.DB;
using RpcExtendModel.Trace;
using RpcHelper;
using RpcModel;

namespace RpcExtend.Collect.Collect
{
    [RpcClient.Attr.ClassLifetimeAttr(RpcClient.Attr.ClassLifetimeType.单例)]
    internal class TraceCollect : ITraceCollect
    {
        private readonly IDelayDataSave<RpcTrace> _DelaySave;
        private readonly IUnityCollect _Unity;
        public TraceCollect(IUnityCollect unity)
        {
            this._Unity = unity;
            this._DelaySave = new DelayDataSave<RpcTrace>(_Save, 2, 10);
        }
        private void _Save(ref RpcTrace[] datas)
        {
            this._Unity.Resolve<IRpcTraceListDAL>().Adds(datas);
        }

        public void Add(SysTraceLog log, MsgSource source)
        {
            if (!log.ParentId.HasValue)
            {
                _DelaySave.AddData(new RpcTrace
                {
                    TraceId = log.TraceId,
                    BeginTime = log.Begin,
                    EndTime = log.End,
                    Duration = log.Duration,
                    RegionId = source.RegionId,
                    ServerId = source.ServerId,
                    SystemType = source.SystemType,
                    ServerName = log.ServerName,
                    Id = Tools.NewGuid()
                });
            }
        }
    }
}
